<template>
  <div class="header-box"
 >
    <a-menu mode="horizontal" :wrap="false"
            :selected-keys="selectKey"
            @menu-item-click="changeNav">
      <a-menu-item key="0" :style="{ padding: 0, marginLeft: '38px' }" disabled>
        <img
          alt="Vue
          logo" src="../assets/logo.png"
          :style="{
          width: '50px',
          height: '50px',
          borderRadius: '2px',
          background: 'var(--color-fill-3)',
          cursor: 'text',
        }"
        />
        <span style="font-size: 30px">
          YOJ
        </span>
        <a-menu-item v-for="menuItem in visibleRoutesArr"
        :key="menuItem?.path">
          <a-space v-if="menuItem.meta !== AccessEnum.UNSHOW">
            <span v-if="!menuItem.path?.startsWith('/user')">
              {{menuItem?.name}}
            </span>
          </a-space>
        </a-menu-item>
        <a-menu-item key="/user/login" style="margin-left: 80vh">
          <a-dropdown trigger="hover"
                      v-if="store.state.user.curUser?.userRole!=AccessEnum.NOT_LOGIN"
                      @select="logout">
            <a-button >
              {{curUser?.userName}}
            </a-button>
            <template #content>
              <a-doption>退出登录</a-doption>
            </template>
          </a-dropdown>
          <a-button v-else>
            登录 / 注册
          </a-button>
        </a-menu-item>
      </a-menu-item>
    </a-menu>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import AccessEnum from "@/access/accessEnum";
import store from "@/store";
import router from "@/router";
import { routes } from "@/router/routes";

const selectKey = ref(['/'])

const curUser = computed(() => store.state?.user?.curUser)
let changeNav = (key: string) => {
  console.log('key', key);
  // 登录需要特判
  if (key === '/user') {
    key = '/user/login';
  }
  // 根据key拿path
  router.push({
    path: key
  });
};

router.afterEach((to, from, failure) => {
  if (to.path === '/user') {
    selectKey.value = ['/user/login'];
  } else {
    selectKey.value = [to.path];
  }
})

// 去登录页面
const toLogin = () => {
  if (!curUser.value.username) {
    router.push({path: '/user/login'})
  }
}

const visibleRoutesArr =
  computed(() =>
    routes.filter(it => it.meta?.access!= AccessEnum.UNSHOW && (it.meta?.access !== AccessEnum.ADMIN || store.state.curUser?.role == AccessEnum.ADMIN))
)
const logout = () => {
  console.log('logout');
  sessionStorage.setItem("token", null);
  router.push({
    path: '/user/login'
  })
}
</script>

<style scoped>
.header-box {
  font-weight: bolder;
  border-bottom: 4px solid rgba(211, 211, 211, 0.45);

}

</style>